package com.museum.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.museum.entity.SystemSettings;
import com.museum.mapper.SystemSettingsMapper;
import com.museum.service.SystemSettingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统设置适配器服务实现
 * 用于适配key-value格式的settings表和SystemSettings实体类
 */
@Service("systemSettingsServiceKeyValue")
public class SystemSettingsServiceAdapter extends ServiceImpl<SystemSettingsMapper,SystemSettings> implements SystemSettingsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Override
    public SystemSettings getSettings() {
        // 从key-value格式的settings表中读取数据
        List<Map<String, Object>> settingsList = jdbcTemplate.queryForList(
                "SELECT `key`, `value` FROM system_settings");
        
        // 创建系统设置对象
        SystemSettings settings = new SystemSettings();
        settings.setId(1L); // 默认ID
        
        // 设置默认值
        settings.setMuseumName("博物馆");
        settings.setOpenTime("周二至周日 9:00-17:00");
        settings.setContactPhone("400-123-4567");
        settings.setAddress("博物馆地址");
        settings.setMaxReservation(200);
        settings.setCreateTime(LocalDateTime.now());
        settings.setUpdateTime(LocalDateTime.now());
        
        // 从数据库读取的值覆盖默认值
        for (Map<String, Object> settingItem : settingsList) {
            String key = (String) settingItem.get("key");
            String value = (String) settingItem.get("value");
            
            switch (key) {
                case "site_name":
                case "museum_name":
                    settings.setMuseumName(value);
                    break;
                case "open_time":
                    settings.setOpenTime(value);
                    break;
                case "contact_phone":
                    settings.setContactPhone(value);
                    break;
                case "address":
                    settings.setAddress(value);
                    break;
                case "max_reservation":
                case "reservation_limit":
                    try {
                        settings.setMaxReservation(Integer.parseInt(value));
                    } catch (NumberFormatException e) {
                        // 使用默认值
                    }
                    break;
            }
        }
        
        return settings;
    }
    
    @Override
    @Transactional
    public boolean updateSettings(SystemSettings settings) {
        try {
            // 使用Map存储要更新的key-value
            Map<String, String> updateValues = new HashMap<>();
            updateValues.put("site_name", settings.getMuseumName());
            updateValues.put("museum_name", settings.getMuseumName());
            updateValues.put("open_time", settings.getOpenTime());
            updateValues.put("contact_phone", settings.getContactPhone());
            updateValues.put("address", settings.getAddress());
            updateValues.put("max_reservation", String.valueOf(settings.getMaxReservation()));
            updateValues.put("reservation_limit", String.valueOf(settings.getMaxReservation()));
            
            // 更新数据库
            for (Map.Entry<String, String> entry : updateValues.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                
                // 检查是否存在该key
                int count = jdbcTemplate.queryForObject(
                        "SELECT COUNT(*) FROM system_settings WHERE `key` = ?", 
                        Integer.class, key);
                
                if (count > 0) {
                    // 更新已存在的key
                    jdbcTemplate.update(
                            "UPDATE system_settings SET `value` = ?, `update_time` = NOW() WHERE `key` = ?", 
                            value, key);
                } else {
                    // 插入新key
                    jdbcTemplate.update(
                            "INSERT INTO system_settings (`key`, `value`, `description`) VALUES (?, ?, ?)",
                            key, value, "系统设置");
                }
            }
            
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean save(SystemSettings entity) {
        return updateSettings(entity);
    }

    @Override
    public boolean updateById(SystemSettings entity) {
        return updateSettings(entity);
    }
} 